<template>
  <div class="the-list">

    <div class="panel-table">
      <div class="table-head">
        <div>
          banner列表
        </div>
        <div>
          <el-button type="primary" @click="sortFn.openPanel">排序</el-button>
          <el-button type="primary" @click="operateFn.openPanel('add')">新增</el-button>
        </div>
      </div>

      <el-table :data="table.list" stripe :header-cell-style="{backgroundColor:'#ededed',padding:'12px 0'}" style="width: 100%;" border>
        <el-table-column prop="sort" label="排序" width="80px"/>

        <el-table-column prop="location" label="banner位置">
          <template #default="{row}">
            {{getItemFromArray(configList.bannerLocation,row.location)}}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="banner名称" />
        <el-table-column prop="imageUrl" label="banner图片" width="106px">
          <template #default="{row}">
            <div v-if="row.imageUrl" @click="imageViewer({initialIndex: 0,urlList: [row.imageUrl]});">
              <el-image style="width: 80px;height: 45px;display:block;" fit="contain" :src="row.imageUrl"/>
            </div>
            <p v-else>--</p>
          </template>
        </el-table-column>
        <el-table-column prop="jumpAddress" label="跳转地址" />
        <el-table-column prop="createdAt" label="上传时间" />
        <el-table-column prop="endTime" label="有效期至" />
        <el-table-column prop="status" label="当前状态" >
          <template #default="{row}">
            <p v-if="row.status===0" class="color-orange">已下架</p>
            <p v-else-if="row.status===1" class="color-green">可用</p>
          </template>
        </el-table-column>

        <el-table-column prop="clickNum" label="PV" />

        <el-table-column fixed="right" label="操作" width="80px">
          <template #default="{row}">
            <el-button size="small" type="primary" plain @click="operateFn.openPanel('edit',row)">编辑</el-button>
            <!-- <el-button v-if="row.status === 0" size="small" type="success" plain>上架</el-button>
            <el-button v-else size="small" type="warning" plain>下架</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <div class="table-pagination">
        <pagination :total="table.total" v-model:page="table.query.page" v-model:limit="table.query.pageSize" @pagination="tableFn.getTableData" />
      </div>

    </div>

    <el-dialog title="banner排序" v-model="sort.showPanel" width="50%" :close-on-click-modal="false" :before-close="sortFn.closePanel">
      <div class="panel-table">

        <div class="table-head">
          <el-select v-model="sort.query.location" placeholder="banner位置" @change="sortFn.locationChange">
            <el-option v-for="item in configList.bannerLocation" :key="item.key" :label="item.name" :value="item.key" @change="sortFn.locationChange"/>
          </el-select>
        </div>

        <el-table :data="sort.list" stripe :header-cell-style="{backgroundColor:'#ededed',padding:'12px 0'}" style="width: 100%;" border>
          <el-table-column prop="sort" label="排序" width="180px">
            <template #default="{row}">
              <el-input-number v-model="row.sort" :max="9999" :min="0" controls-position="right" @change="sortFn.sortChange($event,row.id)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="banner名称" />
          <el-table-column prop="imageUrl" label="banner图片" width="106px">
            <template #default="{row}">
              <div v-if="row.imageUrl" @click="imageViewer({initialIndex: 0,urlList: [row.imageUrl]});">
                <el-image style="width: 80px;height: 45px;display:block;" fit="contain" :src="row.imageUrl"/>
              </div>
              <p v-else>--</p>
            </template>
          </el-table-column>
        </el-table>


      </div>
      <div class="table-foot" style="margin: 12px;text-align:right;">
        <el-button type="primary" plain @click="sortFn.closePanel">取消</el-button>
        <el-button type="primary" :disabled="sort.postMap.size===0" @click="sortFn.submitData">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog title="新增/编辑" v-model="operate.showPanel" width="70%" :close-on-click-modal="false" :before-close="operateFn.closePanel">
          
        <el-form v-loading="operate.isLoading" ref="formRef" :rules="formRules" :model="operate.post" class="demo-form-inline" label-width="140px">

          <el-form-item prop="location" label="banner位置">
            <el-select v-model="operate.post.location" placeholder="banner位置">
              <el-option v-for="item in configList.bannerLocation" :key="item.key" :label="item.name" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item prop="name" label="banner名称">
            <el-input v-model="operate.post.name" style="max-width:420px;" placeholder="banner名称"></el-input>
          </el-form-item>
          <el-form-item prop="jumpAddress" label="跳转地址">
            <el-input v-model="operate.post.jumpAddress" style="max-width:420px;" placeholder="跳转地址"></el-input>
          </el-form-item>

          <el-form-item prop="imageUrl" label="banner图片">
            <inputUpload v-model="operate.post.imageUrl"></inputUpload>
          </el-form-item>

          <el-form-item prop="endTime" label="报名截止时间">
            <el-radio-group v-model="operate.otherData.timeType" @change="operateFn.timeTypeChange">
              <el-radio :label="1">长期有效</el-radio>
              <el-radio :label="2">有效期至</el-radio>
            </el-radio-group>
            <div style="display:inline-block;margin:0 24px;" v-show="operate.otherData.timeType===2">
              <el-date-picker v-model="operate.post.endTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="选择日期时间"></el-date-picker>
            </div>
          </el-form-item>

          <el-form-item prop="status" label="状态">
            <el-switch :width="56" style="--el-switch-off-color: #aaaaaa" v-model="operate.post.status" :active-value="1" :inactive-value="0" inline-prompt active-text="可用" inactive-text="下架"></el-switch>
          </el-form-item>

          <el-form-item style="text-align:center">
            <el-button type="primary" plain @click="operateFn.closePanel">取消</el-button>
            <el-button type="primary" plain @click="operateFn.submitPre(formRef)">提交</el-button>
          </el-form-item>
        </el-form>

    </el-dialog>

  </div>
</template>

<script setup>
import { reactive, ref, watchEffect } from "vue";

import { getBannerList,getBannerSortList,modifyBannerSort,addBanner,modifyBanner } from "@/api/config";
import { ElMessage, ElMessageBox } from "element-plus";
import Pagination from "@/components/Pagination";
import { useRouter } from "vue-router";
import { configList,getItemFromArray,isLongTime } from "@/utils/tool";
import imageViewer from "@/components/imageViewer/index2";

const router = useRouter();

const params = ref({});
const query = ref({});

const formRef = ref();
const formRules = reactive({
  location: [{ required: true, message: "请选择banner位置", trigger: "change" }],
  name: [{ required: true, message: "请填写banner名称", trigger: "blur" }],
  // jumpAddress: [{ required: true, message: "请填写跳转地址", trigger: "blur" }],
  endTime: [{ required: true, message: "请选择结束时间", trigger: ["change","blur"] }],
  imageUrl: [{ required: true, message: "请填写或上传图片", trigger: "blur" }],
});

watchEffect(()=>{
  params.value = router.currentRoute.value.params;
})
watchEffect(()=>{
  query.value = router.currentRoute.value.query;
})

// 评论的表格功能模块，包括搜索，分页和表格体等
const { $data: table, $fn: tableFn } = (() => {
  const router = useRouter();
  const backup = {
    query: {
      pageSize: 10,
      page: 1,
    },
  };

  const $data = reactive({
    query: { ...backup.query },
    list: [],
    total: 0,
  });
  const $fn = {
    getTableData() {
      getBannerList($data.query).then((res) => {
        if (res.code === 0) {
          $data.list = res.data.items;
          $data.total = res.data.pagination.total_record;
        }
      });
    },
    onResetQuery() {
      $data.query = { ...backup.query };
      $fn.getTableData();
    },
    onSubmit() {
      $fn.getTableData();
    },
  };
  $fn.getTableData();
  return {
    $data,
    $fn,
  };
})();
// 回复的表格模块，包括分页和表格体
const { $data: sort, $fn: sortFn } = (() => {
  const $static = {
    listData:{},//列表数据备份
  }
  const $data = reactive({
    showPanel: false,
    query: {
      location: "",
    },
    hasModify: false,
    postMap: new Map(),
    list: [],
    
  });
  const $fn = {
    getTableData() {
      let loc = $data.query.location;
      if(!loc)return;
      if($static.listData[loc]){
        console.log("本地缓存获取！",loc);
        $data.list = [...$static.listData[loc]];
        return;
      }
      console.log("服务器获取！",loc);
      getBannerSortList($data.query).then((res) => {
        if (res.code === 0) {
          $static.listData[loc] = JSON.parse(JSON.stringify(res.data||[]));
          $data.list = res.data;
        }
      });
    },
    openPanel() {
      $data.showPanel = true;
    },
    closePanel() {
      $data.showPanel = false;
      $data.query.location = "";
      $data.list = [];
      $static.listData = {};
    },
    sortChange(sort,id){
      let oValue = getItemFromArray( $static.listData[$data.query.location],id,{key:"id",name:"sort"});
      if(sort === oValue){
        $data.postMap.delete(id);
      }else{
        $data.postMap.set(id,{sort,id});
      }
    },
    locationChange(value){
      $data.query.location = value;
      $data.hasModify = false;
      $data.postMap.clear();
      $fn.getTableData();
    },
    submitData(){
      let req = [
        ...$data.postMap.values(),
      ]
      modifyBannerSort(req).then(res=>{
        if(res.code===0){
          ElMessage.success("修改成功！");
          tableFn.getTableData();
          $fn.closePanel();
        }
      })
    }
  };
  return {
    $data,
    $fn,
  };
})();
// 新增、编辑
const { $data: operate, $fn: operateFn } = (() => {
  const $static = {
    post: {
      location: "",//位置，活动中心：activity_center；我的：mine
      name: "",//名字
      jumpAddress: "",//跳转地址
      endTime: "",//结束时间，永久有效 默认为 2300-01-01 00:00:00
      imageUrl: "",//图片地址
      status: 0,//状态0、已下架；1、上架
    },
  }
  const $data = reactive({
    showPanel: false,
    isEdit: false,
    isLoading: false,
    post: {...$static.post},
    otherData:{
      timeType: 2,//1：长期（2300年），2：选定时间
    }
  });
  const $fn = {
    openPanel(type,row){
      if(type==='edit'){
        $data.isEdit = true;
        $data.post = {...row};
        $data.otherData.timeType = isLongTime(row.endTime)?1:2;
      }else{
        $data.isEdit = false;
      }
      $data.showPanel = true;
    },
    closePanel(){
      console.log("close panel!");
      $data.showPanel = false;
      $data.post = {...$static.post};
      $data.otherData.timeType = 2;
      $data.isLoading = false;
      formRef.value.resetFields();
    },
    submitPre(formRef){
      if (!formRef) return;
      formRef.validate((valid) => {
        if (valid) {
          $fn.submitData();
        }
      });
    },
    submitData(){
      // $data.isLoading = true;
      let req = {
        ...$data.post,
      }
      console.log("req:",req);
      // return;
      $data.isLoading = true;
      if($data.isEdit){
        modifyBanner(req).then(res=>{
          if(res.code===0){
            ElMessage.success("修改成功！");
            $fn.closePanel();
            tableFn.getTableData();
          }
        })
      }else{
        addBanner(req).then(res=>{
          if(res.code===0){
            ElMessage.success("添加成功！");
            $fn.closePanel();
            tableFn.getTableData();
          }
        })
      }
    },
    timeTypeChange(type){
      if(type===1){
        $data.post.endTime = "2300-01-01 00:00:00";
      }else{
        $data.post.endTime = null;
      }
    },
    limitEndDate(time){
      // 今天~2300年
      const beginDate = new Date().getTime();
      const endDate = new Date('2300-01-01 00:00:00').getTime() - 8.64e7
      return beginDate > time.getTime() || endDate < time.getTime();
    }
  };
  return {
    $data,
    $fn,
  };
})();
</script>

<style scoped lang="scss">
@import "@/styles/tablePage.scss";
</style>